<template>
  <div style="display: flex;justify-content: center;align-items: center">
    <el-select
      :value="value"
      v-model="copyValue"
      :filterable="filterable"
      :clearable="clearable"
      remote
      :remote-method="query01"
      :multiple="multiple"
      :placeholder="placeholder"
      :autocomplete="autoComplete || autocomplete"
      :size="size"
      :disabled="disabled"
      :collapse-tags="collapseTags"
      :allow-create="allowCreate"
      style="width:100%;"
      @change="updateValue"
      @focus="focusHandler"
      @visible-change="queryUrl"
    >
      <div slot="empty" v-if="jsonAdd">
        <div style="padding: 10px">
          <el-input
            v-model="keyword"
            :placeholder="url?'请输入内容搜索':'输入内容回车可创建'"
            style="margin: auto"
            class="input-with-select"
            @keyup.enter.native="addNewItem"
          />
        </div>
      </div>

      <!--      <div style="padding: 10px">-->
      <!--        <el-input-->
      <!--          ref="ipt"-->
      <!--          v-model="keyword"-->
      <!--          :placeholder="url?'请输入内容搜索':'输入内容回车可创建'"-->
      <!--          style="margin: auto"-->
      <!--          class="input-with-select"-->
      <!--          @keyup.enter.native="addNewItem"-->
      <!--        />-->
      <!--      </div>-->

      <!--      <el-option-group v-if="oldLabel" label="上次选择的值">-->
      <!--        <el-option-->
      <!--          :label="oldLabel"-->
      <!--          :value="copyValue"-->
      <!--        />-->
      <!--      </el-option-group>-->

      <!--      <el-option-group v-if="multiple" label="可选值1">-->
      <!--        <el-option-->
      <!--          v-for="item in dataList"-->
      <!--          :key="item.value"-->
      <!--          :label="item[labelKey]"-->
      <!--          :value="item[valueKey] + ''"-->
      <!--        />-->
      <!--      </el-option-group>-->
      <el-option-group  label="可选值1">
        <div v-if="url === 'api/dropDown/basCustomerList'" class="flex flex-row  select_title" style="padding-left: 20px">
          <div class="fl1">编号</div><div class="fl2">名称</div><div class="fl3">地址</div>
        </div>
        <el-option
          v-for="(item,index) in dataList"
          :key="index"
          :label="item[labelKey]"
          :value="item[valueKey]"
        >
          <div v-if="url === 'api/dropDown/basCustomerList'"  :class="{'rowOne':(index % 2)}" class="flex flex-row select_customer_li">
            <div class="fl1">{{ item.code }}</div><div class="fl2">{{ item.name }}</div><div class="fl3">{{ item.address }}</div>
          </div>
        </el-option>
      </el-option-group>
      <div v-if="url" style="float: right;margin-right:10px;padding-bottom: 10px">
        <el-pagination
          :current-page="pageInfo.page"
          :page-size="pageInfo.size"
          layout="total, prev, pager, next"
          :total="pageInfo.total"
          :pager-count="5"
          @current-change="handleCurrentChange"
        />
      </div>

    </el-select>
  </div>

</template>

<script>
import request from '@/utils/request'

export default {
  name: 'ZSelect',
  props: {
    // 绑定值
    value: [String, Number, Object, Array],
    disabled: {
      type: Boolean,
      default: false
    },
    label: {
      default: '', // 已经选中的值内容
      type: String
    },
    url: String, // 如果不传url,则使用自定义模式
    json: String, // 没有url时，这个json不能为空，且要有isSelect字段
    // option的label在列表中对应的key
    labelKey: {
      type: String,
      default: 'name'
    },
    // option的value在列表中对应的key
    valueKey: {
      type: String,
      default: 'id'
    },
    isLast:{
      type:Boolean,
      default:false
    },
    // 参数
    params: {
      type: Object,
      default: function() {
        return {}
      }
    },
    // 其他参数
    autocomplete: {
      type: String,
      default: 'off'
    },
    /** @Deprecated in next major version */
    autoComplete: {
      type: String,
      validator(val) {
        process.env.NODE_ENV !== 'production' &&
        console.warn('[Element Warn][Select]\'auto-complete\' property will be deprecated in next major version. please use \'autocomplete\' instead.')
        return true
      }
    },
    automaticDropdown: Boolean,
    size: String,
    clearable: {
      type:Boolean,
      default: true
    },
    filterable: {
      type:Boolean,
      default:true
    },
    allowCreate: Boolean,
    loading: Boolean,
    popperClass: String,
    remote: Boolean,
    loadingText: String,
    noMatchText: String,
    noDataText: String,
    remoteMethod: Function,
    filterMethod: Function,
    multiple: Boolean,
    multipleLimit: {
      type: Number,
      default: 0
    },
    placeholder: {
      type: String,
      required: false,
      default: '请选择'
    },
    defaultFirstOption: Boolean,
    reserveKeyword: Boolean,
    collapseTags: {
      type:Boolean,
      default:false
    },
    popperAppendToBody: {
      type: Boolean,
      default: true
    },
    // 数据实际层级
    dataKey: {
      type: String,
      default: ''
    },
    // 翻页参数实际层级
    dataTotalKey: {
      type: String,
      default: ''
    },
    // 翻页参数实际层级
    showName: {
      type: String,
      default: ''
    },
    jsonAdd: {
      type:Boolean,
      default:false
    },
  },
  data() {
    return {
      copyValue: this.value ? typeof (this.value) === 'string' ? this.value.split(',') : this.value : this.value,
      keyword: '',
      // 下拉列表
      dataList: [],
      oldLabel: '',
      pageInfo: {
        page: 1,
        size: 6,
        total: 0
      }
    }
  },
  mounted() {
    this.addSelect()
  },

  watch: {
    value: {
      handler: function(val) {
        // const copyValue = this.multiple ? typeof (val) === 'string' ? val.split(',') : typeof (val) === 'string' : val
        if (this.multiple){
          if (this.copyValue === this.value || this.value === this.copyValue.join(',')){
            return false
          }
          if (typeof val === 'string'){this.copyValue = val.split(',')}
          else if(typeof val === undefined){
            this.$emit('update:value','');
            this.copyValue=[]
          }else if(val.length === 0){
            this.copyValue=[]
          }
        }else {
          this.copyValue = this.value
        }
        // if (!this.labelKey){
        //   return
        // }
        // if(this.multiple){
        //   return;
        // }
        this.oldLabel = this.label
        this.addSelect()
      },
      deep: true
    },
    // copyValue: {
    //   handler(n,o){
    //     if (!this.copyValue.length){
    //       return
    //     }
    //     const list = []
    //     for(let i in this.copyValue){
    //       console.log(this.dataList.find(item => this.copyValue[i] === item.id))
    //       const {id, name ,code} = this.dataList.find(item => this.copyValue[i] === item.id)
    //       list.push({id, name ,code})
    //     }
    //     this.$emit('objectList',list)
    //   },
    //   deep:true
    // },

    // showName(n,o){
    //   this.dataList = []
    //   const data={}
    //   if (!this.labelKey){
    //     return
    //   }
    //   data[this.labelKey] = this.showName
    //   data[this.valueKey] = this.value
    //   this.dataList.push(data)
    // },


    // params: {
    //   handler: function(val) {
    //     // 如果有一个是undefined,则不查询
    //     for (const key in val) {
    //       if (!val[key]) {
    //         return false
    //       }
    //     }
    //     this.getList()
    //   },
    //   deep: true
    // },
    // keyword: function(n) {
    //   // this.pageInfo.page = 1
    //   this.getList(n)
    // },
    // url: function(n) {
    //   // this.pageInfo.page = 1
    //   this.getList(n)
    // },
    json: function(n) {
      this.detailJson()
    }

  },
  // mounted() {
  //   if (this.url) {
  //     this.getOne()
  //     this.getList()
  //   } else {
  //     this.detailJson()
  //   }
  // },
  methods: {
    addSelect(){
      setTimeout(()=>{
          if (this.value){
            try{
              this.copyValue = this.value
              if (this.multiple){
                const labelKey = this.showName.split(',')
                if (labelKey.length !== this.copyValue.length){
                  return
                }
                for (let i = 0;i<this.copyValue.length;i++){
                  const data={}
                  data[this.labelKey] = labelKey[i]
                  data[this.valueKey] = this.copyValue[i]
                  if(!this.dataList.find(item=>item[this.valueKey] === this.copyValue[i])){
                    this.dataList.push(data)
                  }
                }
              }else {
                if (this.showName){
                  const data={}
                  data[this.labelKey] = this.showName
                  data[this.valueKey] = this.copyValue
                  this.$set(this.dataList, 0, data)
                }
              }
              this.$forceUpdate()
            }catch (e){
              console.error(e)
            }
          }},
        100)
    },
    query01(query){
      this.keyword = query
      this.getList(query)
    },
    detailJson() {
      if (this.json) {
        this.dataList = JSON.parse(this.json)
      }
      const obj = this.dataList.find(data => {
        return data.isSelected
      })
      if (obj) {
        this.copyValue = obj[this.valueKey]
      }
    },
    addNewItem() {
      const obj = {
        [this.valueKey]: this.keyword,
        [this.labelKey]: this.keyword,
        isSelected: false
      }
      if (!this.url) {
        // 没有传url，就用自定义方式
        this.dataList.push(obj)
      }
      this.$forceUpdate()
    },
    getOne() {
      if (!this.copyValue) {
        return false
      }
      let params = {}
      // if (this.multiple) {
      //   params = {
      //     ids: this.copyValue.length > 0 ? this.copyValue.json(',') : this.copyValue
      //   }
      // } else {
      //   params = {
      //     id: this.copyValue
      //   }
      // }
      request({
        url: this.url,
        method: 'get',
        params
      }).then(res => {
        let _data = res.data
        if (this.dataKey) {
          const keyStr = this.dataKey.split('.').reduce((a, b) => a + `['${b}']`, '')
          // eslint-disable-next-line no-eval
          _data = eval('(res' + keyStr + ')')
        } else {
          // 兼容之前接口
          if (res.content) {
            _data = res.content
          }
        }
        if (_data.length) this.oldLabel = _data[0][this.labelKey]
      })
    },

    getList(n) {
      // eslint-disable-next-line eqeqeq
      if (this.url == null || this.url == '') {
        return false
      }
      const oldList = []
      if (this.multiple){
        this.dataList.forEach(item=>{
          if (this.copyValue.includes(item[this.valueKey])){
            oldList.push(item)
          }
        })
      }
      // 使用url查询
      const params = Object.assign({
        page: this.pageInfo.page,
        size: this.pageInfo.size
      }, this.params)
      if (this.keyword) {
        params['keyword'] = this.keyword
      }
      if (n == '') {
        params['keyword'] = this.keyword
      }
      if (this.isLast){
        params['isLast']=1
      }
      request({
        url: this.url,
        method: 'get',
        params
      }).then(res => {
        let _data = res.data
        // eslint-disable-next-line no-eval
        if (this.dataKey) _data = eval('(res' + this.getKeyString(this.dataKey) + ')')
        else {
          // 兼容之前接口
          if (res.content) {
            _data = res.content
          }
        }
        // 将data中的id由int 转为string
        // for (let da of _data) {
        //   da.id=(da.id+"")
        // }
        this.dataList = oldList.concat(_data)

        //去重
        this.dataList = this.uniqObjInArray(this.dataList)
        this.$forceUpdate()
        // eslint-disable-next-line no-eval
        if (this.dataTotalKey) this.pageInfo.total = eval('(res' + this.getKeyString(this.dataTotalKey) + ')')
        else this.pageInfo.total = res.totalElements
      })
    },
    // 获取对应的key的字符串拼接
    getKeyString(string = '') {
      if (!string) return []
      else return string.split('.').reduce((a, b) => a + `['${b}']`, '')
    },
    // 更新值
    updateValue(_data) {
      //
      if (!this.copyValue.length){
        return
      }
      const list = []
      for(let i in this.copyValue){
        console.log(this.dataList.find(item => this.copyValue[i] === item.id))
        const {id, name ,code} = this.dataList.find(item => this.copyValue[i] === item.id)
        list.push({id, name ,code})
      }
      this.$emit('objectList',list)
    },
    // 翻页
    handleCurrentChange(val) {
      this.pageInfo.page = val
      this.getList()
    },
    focusHandler() {
      this.$emit('focus')
    },
    //下拉才请求接口
    queryUrl(val){
      if (val){
        // setTimeout(()=>{this.$refs.ipt.$el.querySelector('input').focus()},500)
        if (this.url) {
          this.getOne()
          this.getList()
        } else {
          this.detailJson()
        }
      }
    },
    uniqObjInArray(objarray){
      let len = objarray.length; //数组长度
      let tempJson = {};//缓存对象
      let res = [];//中间数组


      for(let i = 0;i < len;i++){
        //利用缓存对象的属性去重
        if(!tempJson[JSON.stringify(objarray[i])]){
          res.push(objarray[i]);
          tempJson[JSON.stringify(objarray[i])] = true;
        }
      }
      return res;
    }

  }

}

</script>

<style  lang="scss" scoped>
.flex{
  display: flex;
}
.flex-row{
  flex-direction: row;
}
.fl1{
  width: 100px;
  overflow: hidden;
}
.select_title{
  height: 40px;
  div{
    border: rgb(200,200,200) solid 1px;
    display: flex;
    align-items: center;
    justify-content: center;
  }
}
.select_customer_li{
  border: rgb(200,200,200) 1px solid;
  div{
    border: rgb(200,200,200) solid 1px;
  }
}
.rowOne{
  background-color: rgba(192,250,233,0.3);
}
.fl2{
  width: 350px;
  overflow: hidden;
}
.fl3{
  width: 150px;
  overflow: hidden;
}
.add{
  padding : 30px;
}
</style>

